//
//  NewsViewController.m
//  ToYourHeartNews
//
//  Created by XJing on 16/1/17.
//  Copyright © 2016年 www.lanou3g.com 蓝鸥. All rights reserved.
//

#import "NewsViewController.h"
#import "MyCollectionViewCell.h"
#import <AFNetworking.h>
#import <UIImageView+WebCache.h>
#import "LunbotuDetailViewController.h"
#import "AfNetWorkingHandler.h"
#import "MyselfViewController.h"
#import "CellDetailViewController.h"
#import "AllModel.h"
#import "AllKindViewController.h"
#import "CarouselPicture.h"//轮播图
#import "SetBlack.h"
#import "BlackManager.h"
#import "SearchViewController.h"
#import "MBProgressHUDManager.h"//小菊花
#import "PushWebViewVC.h"
#import "MyselfViewController.h"
#define kuan  [UIScreen mainScreen].bounds.size.width / 375
#define gao [UIScreen mainScreen].bounds.size.height / 667
@interface NewsViewController ()<UICollectionViewDataSource, UICollectionViewDelegate, UIScrollViewDelegate, CarouselPictureDelegate>
@property (nonatomic, retain)UICollectionView *collection;
@property (nonatomic, retain)UIView *lunboView;
@property (nonatomic, retain)UIScrollView *photos;//轮播图
@property (nonatomic, retain)NSMutableArray *lunboArr;//存放轮播图图片
@property (nonatomic, retain)NSMutableArray *lunboTitle;//存放轮播图标题
@property (nonatomic, retain)NSMutableArray *lunboId;//详情页需要拼接的id
@property (nonatomic, retain)NSTimer *timer;
@property (nonatomic, retain)UIPageControl *page;
@property (nonatomic, assign)CGFloat distance;
@property (nonatomic, retain)NSMutableArray *allArr;//存放Zaker所有数据

@end

@implementation NewsViewController
-(void)dealloc
{
    [_collection release];
    [_lunboView release];
    [_photos release];
    [_lunboArr release];
    [_lunboTitle release];
    [_lunboId release];
    [_timer release];
    [_page release];
    [_allArr release];
    [super dealloc];
}
- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
   
    //设置按钮
    self.navigationItem.rightBarButtonItem = [[[UIBarButtonItem alloc]initWithBarButtonSystemItem:UIBarButtonSystemItemSearch target:self action:@selector(searchAction)] autorelease];
    self.navigationItem.title = @"新闻";
    self.navigationItem.leftBarButtonItem = [[[UIBarButtonItem alloc]initWithImage:[UIImage imageNamed:@"iconfont-my"] style:UIBarButtonItemStylePlain target:self action:@selector(myAction)]autorelease];
    //设置按钮颜色
//    self.navigationController.navigationBar.tintColor = [UIColor grayColor];
    //colection
    UICollectionViewFlowLayout *layout = [[UICollectionViewFlowLayout alloc]init];
    layout.minimumInteritemSpacing = 10 * gao;
    layout.minimumLineSpacing = 10 * kuan;
    layout.sectionInset = UIEdgeInsetsMake(0, 10 * kuan, 0, 10 * kuan);
    layout.itemSize = CGSizeMake(( self.view.frame.size.width - 40 - 20) * kuan   / 3 , ( self.view.frame.size.width - 40 - 20 ) * kuan / 3 );
    layout.scrollDirection = UICollectionViewScrollDirectionVertical;
    layout.headerReferenceSize = CGSizeMake(self.view.frame.size.width, 270 );
    
    self.collection = [[UICollectionView alloc] initWithFrame:self.view.frame collectionViewLayout:layout];
    _collection.dataSource = self;
    _collection.delegate = self;
    _collection.bounces = NO;
    _collection.alwaysBounceHorizontal = NO;
    _collection.alwaysBounceVertical = YES;
    _collection.backgroundColor = [UIColor whiteColor];
    _collection.contentInset = UIEdgeInsetsMake(0, 0, 64, 0);
    [self.view addSubview:_collection];
    [_collection registerClass:[MyCollectionViewCell class] forCellWithReuseIdentifier:@"cell"];
    //内存释放
    [layout release];
    [_collection release];
    
    //数据处理
    [self dataHandler];
    
}

//重写BaseViewController中的方法 设置夜间模式
-(void)setNightDayModel
{
    [SetBlack setBackgroundColorWithView:self.collection];
    self.navigationController.navigationBar.barStyle = UIBarStyleBlack;
    self.tabBarController.tabBar.barStyle = UIBarStyleBlack;
//    //导航栏背景颜色
//    self.navigationController.navigationBar.backgroundColor = [UIColor blackColor];
//    //导航栏上按钮的颜色
//    self.navigationController.navigationBar.tintColor = [UIColor blackColor];
}
-(void)setLightDayModel
{
    [SetBlack setBackgroundColorWithView:self.collection];
    self.navigationController.navigationBar.barStyle = UIBarStyleDefault;
    self.tabBarController.tabBar.barStyle = UIBarStyleDefault;
}
#pragma mark - 创建轮播图
- (void)creatLunbo
{
    self.lunboView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, 240)];
    [_collection addSubview:_lunboView];
    _lunboView.backgroundColor = [UIColor redColor];
    //创建轮播图对象
    CarouselPicture *b = [[CarouselPicture alloc]initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, 240) timeInterval:2 imageUrlArr:_lunboArr urlArr:nil titleArr:_lunboTitle];
    b.delegate = self;
    b.backgroundColor = [UIColor yellowColor];
    [_lunboView addSubview:b];
    [_lunboView release];
    
}
//数据处理
-(void)dataHandler
{
    [MBProgressHUDManager showHUDtoView:self.view string:@"努力加载中"];
    //轮播图的数据   
    NSString *str = @"http://api.app.happyjuzi.com/v2.8.2/article/list/home?net=wifi&page=1&pf=ios&res=320x568&size=20&uid=3931188994231555&ver=2.8.2";
    [AfNetWorkingHandler GetWithStr:str complection:^(id result) {
        NSArray *arr = result[@"data"][@"info"];
        self.lunboArr = [NSMutableArray array];
        self.lunboTitle = [NSMutableArray array];
        self.lunboId = [NSMutableArray array];
        for (NSDictionary *dic in arr) {
            NSString *str = dic[@"pic"];
            NSArray *strArr = [str componentsSeparatedByString:@"!"];
            [self.lunboArr addObject:strArr.firstObject];
            NSString *titlestr = dic[@"title"];
            [self.lunboTitle addObject:titlestr];
            [self.lunboId addObject:dic[@"id"]];
        }
        [self creatLunbo];
        _page.numberOfPages = _lunboArr.count;
        [_collection reloadData];
        [MBProgressHUDManager removeHUD];
    
        
    }];
    //下面collectionView的数据
    NSString *path = @"http://iphone.myzaker.com/zaker/apps_v3.php?_appid=iphone&_version=6.45&act=getAllAppsData";
    [AfNetWorkingHandler GetWithStr:path complection:^(id result) {
        //
        NSArray *all = result[@"data"][@"datas"];
        self.allArr = [AllModel modelHanderWithArray:all];
        [_collection reloadData];
    }];
}

//点击方法 进入详情页
-(void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
    AllKindViewController *VC = [[AllKindViewController alloc]init];
    if (indexPath.item == 0) {
        //新闻
        AllModel *model = _allArr[0];
        VC.allArr = model.sons;
    }
    if (indexPath.item == 1) {
        //娱乐
        AllModel *model = _allArr[1];
        VC.allArr = model.sons;
    }
    if (indexPath.item == 2) {
        //科技
        AllModel *model = _allArr[2];
        VC.allArr = model.sons;
    }
    if (indexPath.item == 3) {
        //时尚
        AllModel *model = _allArr[4];
        VC.allArr = model.sons;
    }
    if (indexPath.item == 4) {
        //心理
        AllModel *model = _allArr[8];
        VC.allArr = model.sons;
    }
    if (indexPath.item == 5) {
        //文艺
        AllModel *model = _allArr[12];
        VC.allArr = model.sons;
    }

    UINavigationController *nav = [[UINavigationController alloc]initWithRootViewController:VC];
    [self presentViewController:nav animated:YES completion:^{
        //
    }];
    [VC release];
    [nav release];
}
//我的按钮的方法
-(void)myAction
{
    MyselfViewController *myself = [[MyselfViewController alloc]init];
    UINavigationController *myselfnav = [[UINavigationController alloc]initWithRootViewController:myself];
    //模态
    [self presentViewController:myselfnav animated:YES completion:^{
        //
    }];
    [myself release];
    [myselfnav release];
}
//轮播图的点击方法
-(void)pushWithUrl:(NSInteger)num
{
    LunbotuDetailViewController *detail = [[LunbotuDetailViewController alloc]init];
    UINavigationController *nav = [[UINavigationController alloc]initWithRootViewController:detail];
     NSNumber *number = _lunboId[num];
     NSString *path = [NSString stringWithFormat:@"http://api.app.happyjuzi.com/v2.8.2/article/detail?id=%ld&net=wifi&pf=ios&res=320x568&uid=3931188994231555&ver=2.8.2", number.integerValue];
    //解析详情页数据
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    [manager GET:path parameters:nil progress:^(NSProgress * _Nonnull downloadProgress) {
        nil;
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        //
        NSDictionary *dic = responseObject[@"data"][@"info"];
        NSString *ss = dic[@"shareurl"];
        detail.pathstr = ss;
        //跳转
        //用push会把前面页的tabbar都带上 所以要用present
        [self presentViewController:nav animated:YES completion:^{
//            [detail release];
//            [nav release];
        }];
        NSLog(@"%@", responseObject);
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        nil;
    }];
    [detail release];
    [nav release];

}
//点击轮播图详情
-(void)tapAction
{
    LunbotuDetailViewController *detail = [[LunbotuDetailViewController alloc]init];
    UINavigationController *nav = [[UINavigationController alloc]initWithRootViewController:detail];
   
    NSNumber *num = _lunboId[_page.currentPage];
    NSString *path = [NSString stringWithFormat:@"http://api.app.happyjuzi.com/v2.8.2/article/detail?id=%ld&net=wifi&pf=ios&res=320x568&uid=3931188994231555&ver=2.8.2", (long)num.integerValue];
    //解析详情页数据
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    [manager GET:path parameters:nil progress:^(NSProgress * _Nonnull downloadProgress) {
        nil;
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        //
        NSDictionary *dic = responseObject[@"data"][@"info"];
        NSString *ss = dic[@"shareurl"];
        detail.pathstr = ss;
        //跳转
        [self presentViewController:nav animated:YES completion:^{
            [detail release];
            [nav release];
        }];
        NSLog(@"%@", responseObject);
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        nil;
    }];
    [detail release];
    [nav release];
}
-(void)searchAction
{
    NSLog(@"搜~");
    SearchViewController *searchVc =[[SearchViewController alloc ]init];
    UINavigationController *nav = [[UINavigationController alloc]initWithRootViewController:searchVc];
    searchVc.dingyueArr = _allArr;
    [self presentViewController:nav animated:YES completion:^{
        //
    }];
    [searchVc release];
    [nav release];
}
-(NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    return 6;
}
//页面出现前更新collectionView
-(void)viewWillAppear:(BOOL)animated
{
    [_collection reloadData];
}
-(UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    MyCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"cell" forIndexPath:indexPath];
    if ([BlackManager sharedInstance].isNight) {
//        [SetBlack setCellColorWithCell:cell];
        cell.lable.textColor = [UIColor whiteColor];
    }else{
//        [SetBlack setCellColorWithCell:cell];
        cell.lable.textColor = [UIColor blackColor];
    }
    if (indexPath.item == 0) {
        cell.img.image = [UIImage imageNamed:@"bagua.png"];
        cell.lable.text = @"新闻";
    }
    if (indexPath.item == 1) {
        cell.img.image = [UIImage imageNamed:@"yaowen.png"];
        cell.lable.text = @"娱乐";
    }
    if (indexPath.item == 2) {
        cell.img.image = [UIImage imageNamed:@"shu.png"];
        cell.lable.text = @"科技";
    }
    if (indexPath.item == 3) {
        cell.img.image = [UIImage imageNamed:@"beike.png"];
        cell.lable.text = @"时尚";
    }
    if (indexPath.item == 4) {
        cell.img.image = [UIImage imageNamed:@"picture.png"];
        cell.lable.text = @"心理";
    }
    if (indexPath.item == 5) {
        cell.img.image = [UIImage imageNamed:@"xixi.png"];
        cell.lable.text = @"文艺";
    }
    return cell;
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
